/*
 * @Date: 2025-03-03 15:17:52
 * @LastEditTime: 2025-03-05 10:52:13
 * @Description:
 * @FilePath: /ranyu_anchor_new/src/plugins/permission.ts
 * @Author: 李梦 2662167563@qq.com
 * @LastEditors: 李梦
 */
// import type { NavigationGuardNext, RouteLocationNormalized, RouteRecordRaw } from "vue-router";
import NProgress from "@/utils/nprogress";
import { getAccessToken, getUserType } from "@/utils/auth";
import router from "@/router";
import { useUserStore } from "@/store"; //usePermissionStore

export function setupPermission() {
  router.beforeEach(async (to, from, next) => {
    NProgress.start(); // 开始进度
    // 1. 未登录用户只能访问登录页面
    if (to.meta.requiresAuth) {
      try {
        //获取认证
        const accessToken = await getAccessToken();
        if (!accessToken) {
          //没登录去登陆
          return next({ path: "/login", replace: true });
        }
        // 2.2 获取用户类型
        const userType = await getUserType();
        if (userType == "3") {
          if (to.path == "/register") {
            return next("/");
          }
          return next();
        } else {
          if (to.path == "/register") {
            return next();
          }
          return next("/register");
        }
      } catch (error) {
        console.log(error);
        return next({ path: "/login", replace: true });
      }
    } else {
      return next();
    }
  });

  // 后置守卫，保证每次路由跳转结束时关闭进度条
  router.afterEach(() => {
    NProgress.done();
  });
}

// 重定向到登录页;
// function redirectToLogin(to: RouteLocationNormalized, next: NavigationGuardNext) {
//   console.log(to);
//   const params = new URLSearchParams(to.query as Record<string, string>);
//   const queryString = params.toString();
//   const redirect = queryString ? `${to.path}?${queryString}` : to.path;
//   next(`/login?redirect=${encodeURIComponent(redirect)}`);
// }

/** 判断是否有权限 */
export function hasAuth(value: string | string[], type: "button" | "role" = "button") {
  const { roles, perms } = useUserStore().userInfo;

  // 超级管理员 拥有所有权限
  if (type === "button" && roles.includes("ROOT")) {
    return true;
  }

  const auths = type === "button" ? perms : roles;
  return typeof value === "string"
    ? auths.includes(value)
    : value.some((perm) => auths.includes(perm));
}
